package com.fram.common.async;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import com.fram.common.auth.UserAuthMethod;
import com.fram.common.redis.RedisService;
import com.fram.common.util.json.JSONTools;
import com.fram.common.util.tencent.TencentUtils;
import com.fram.entity.User;
import com.fram.mapper.UserMapper;

/**
 * @作者： 陳曉鬆 @时间： 2020年8月14日 - 下午3:06:11 @description：->
 */
@Component
@EnableAsync
public class AsyncMethod {

	@Autowired
	private TencentUtils tencentUtils;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RedisService redisService;

	// 设置Unionid
	@Async
	public void settingUnionid(Long userId, String appid, String openid, String transactionId) {
		try {
			User user = userMapper.selectByPrimaryKey(userId);
			if (user != null && StringUtils.isEmpty(user.getUnionid())) {
				String uuid = tencentUtils.getUnionid(appid, openid, transactionId);
				if (!StringUtils.isEmpty(uuid)) {
					User updateUser = new User();
					updateUser.setId(userId);
					updateUser.setUnionid(uuid);
					userMapper.updateByPrimaryKeySelective(updateUser);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 设置极光推送id
	@Async
	public void setRegistrationId(String reidsKey, String json, String registrationId) {
		try {
			// 记录极光推送id
			if (!StringUtils.isEmpty(registrationId) && reidsKey.contains(UserAuthMethod.LOGIN_REDIS_HEADER)) {
				User user = JSONTools.jsonStr2obj(json, User.class);
				if (user != null) {
					boolean isUpdate = true;
					if (!StringUtils.isEmpty(user.getRegistrationId()) && user.getRegistrationId().equals(registrationId)) {
						isUpdate = false;
					}
					if (isUpdate) {
						// 记录到数据库
						User update = new User();
						update.setId(user.getId());
						update.setRegistrationId(registrationId);
						if (userMapper.updateByPrimaryKeySelective(update) > 0) {
							// 更改redis
							user.setRegistrationId(registrationId);
							redisService.set(UserAuthMethod.LOGIN_REDIS_DB, reidsKey, JSONTools.obj2json(user), UserAuthMethod.LOGIN_REDIS_TIME);
						}
					}
				}
			}
		} catch (Exception e) {
		}
	}

}
